package com.felix.forum.dao;

import com.felix.forum.po.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface ArticleRepository extends JpaRepository<Article, Long>, JpaSpecificationExecutor<Article> {

    @Query("select a from Article a where a.recommend = true")
    List<Article> findTop(Pageable pageable);

    @Query("select a from Article a where a.title like ?1 or a.content like ?1")
    Page<Article> findByQuery(String query, Pageable pageable);

    @Transactional
    @Modifying
    @Query("update Article a set a.views = a.views+1 where a.id = ?1")
    int updateViews(Long id);

    /*在归档模块展示博客*/
    /*获取博客年份并显示年份*/
    @Query("select function('date_format',a.updateTime,'%Y') from Article a group by function('date_format',a.updateTime,'%Y') order by function('date_format',a.updateTime,'%Y') desc")
    List<String> findGroupYear();

    /*将博客按年份分组*/
    @Query("select a from Article a where function('date_format',a.updateTime,'%Y') = ?1 and a.published=true")
    List<Article> findByYear(String year);
}
